import os
import subprocess
import download
import shutil

def check_java_installed():
    # 检查是否已安装Java
    try:
        subprocess.run(['java', '-version'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        print("Java已安装，可以继续操作。")
        return True
    except FileNotFoundError:
        print("未检测到Java，需要安装OpenJDK 17。")
        return False

def install_openjdk_17():
    # 使用pkg安装OpenJDK 17
    try:
        print("正在安装OpenJDK 17，请稍候...")
        subprocess.run(['pkg', 'install', '-y', 'openjdk-17'], check=True)
        print("OpenJDK 17安装完成！")
        return True
    except Exception as e:
        print(f"安装OpenJDK 17时出错：{e}")
        return False

def list_and_select_jar():
    # 获取当前目录下所有的jar文件
    jar_files = [file for file in os.listdir('.') if file.endswith('.jar')]
    if not jar_files:
        print("当前目录下没有找到任何.jar文件！")
        return None

    print("当前目录下找到以下.jar文件：")
    for index, jar in enumerate(jar_files, start=1):
        print(f"{index}. {jar}")

    while True:
        try:
            choice = int(input("请输入要启动的jar文件编号："))
            if 1 <= choice <= len(jar_files):
                selected_jar = jar_files[choice - 1]
                print(f"你选择了启动：{selected_jar}")
                return selected_jar
            else:
                print("输入的编号超出范围，请重新输入！")
        except ValueError:
            print("请输入一个有效的数字编号！")

def start_jar(jar_file):
    try:
        print(f"正在启动 {jar_file}...")
        # 使用subprocess启动jar文件，这里假设使用java命令
        subprocess.run(['java', '-jar', jar_file], check=True)
    except Exception as e:
        print(f"启动jar文件时出错：{e}")

def main():
    print("欢迎使用MCOYA")
    while True:
        print("\n请选择操作：")
        print("1. 遍历当前目录所有jar并选择启动")
        print("2. 下载jar核心")
        print("3. 退出")
        choice = input("请输入选项编号：")

        if choice == '1':
            # 检查Java是否已安装
            if not check_java_installed():
                # 如果未安装Java，尝试安装OpenJDK 17
                if not install_openjdk_17():
                    print("Java未安装且安装失败，请手动安装Java后再试。")
                    continue

            selected_jar = list_and_select_jar()
            if selected_jar:
                start_jar(selected_jar)
        elif choice == '2':
            try:
                print("正在下载jar核心文件...")
                download.download()  # 调用download模块的download函数
                print("jar核心下载完成！")
            except Exception as e:
                print(f"下载jar核心时出错：{e}")
        elif choice == '3':
            print("感谢使用，再见！")
            break
        else:
            print("无效的选项，请重新输入！")

if __name__ == "__main__":
    main()
